#include <func.h>

int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,3);
    //创建套接字
    int sock_fd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sock_fd,-1,"sock_fd");

    //定义结构体，存储ip和端口号
    struct sockaddr_in serAddr;
    memset(&serAddr,0,sizeof(serAddr));
    serAddr.sin_family=AF_INET;
    serAddr.sin_addr.s_addr=inet_addr(argv[1]);//inet_addr将点分十进制转换为网络字节序
    //htons将主机字节序转换为网络字节序
    serAddr.sin_port=htons(atoi(argv[2]));//atoi将字符串转换为整数

    int ret;
    //绑定套接字、IP、端口号
    ret=bind(sock_fd,(struct sockaddr *)&serAddr,sizeof(serAddr));
    ERROR_CHECK(ret,-1,"bind");
    
    listen(sock_fd,10);//10是代表链接队列的长度
    struct sockaddr_in clientAddr;//客户端的IP和端口号
    int addrLen=sizeof(clientAddr);
    int new_fd=accept(sock_fd,(struct sockaddr *)&clientAddr,&addrLen);//接收客户端的链接
    ERROR_CHECK(new_fd,-1,"accept");
#ifdef DEBUG
    //打印客户端的IP和端口号
    printf("ip=%s,port=%d\n",inet_ntoa(clientAddr.sin_addr),ntohs(clientAddr.sin_port));
#endif
    fd_set rdset;//用于存储要监视的文件描述符
    char buf[1000];
    while (1)
    {
        FD_ZERO(&rdset);//清零
        FD_SET(STDIN_FILENO,&rdset);//添加标准输入
        FD_SET(new_fd,&rdset);//添加新链接
        select(new_fd+1,&rdset,NULL,NULL,NULL);
        //标准输入可读
        if(FD_ISSET(STDIN_FILENO,&rdset))
        {
            memset(buf,0,sizeof(buf));
            read(STDIN_FILENO,buf,sizeof(buf));
            send(new_fd,buf,strlen(buf)-1,0);//将读到的数据发送给对方
        }
        if(FD_ISSET(new_fd,&rdset))
        {
            memset(buf,0,sizeof(buf));
            ret=recv(new_fd,buf,sizeof(buf),0);
            if(ret==0)
            {
                printf("Client disconnected\n");
                break;
            }
#ifdef DEBUG
            //输出客户端发送过来的内容
            printf("%s\n",buf);
#endif
        }
    }
    close(new_fd);
    close(sock_fd);
    return 0;
}